'''
通用辅助函数模块
'''
import datetime
from flask import g
from psycopg2.extras import RealDictCursor

def format_tasks_tree(tasks, parent_id=None):
    """格式化任务为树形结构的辅助函数"""
    tree = []
    for task in tasks:
        if task['parent_task_id'] == parent_id:
            children = format_tasks_tree(tasks, task['id'])
            if children:
                task['children'] = children
            tree.append(task)
    return tree

def log_task_status_change(sub_task_id, previous_status, new_status, progress=0, comments='', logged_by='system', time_spent=0):
    """记录任务状态变更"""
    conn = g.db
    cursor = conn.cursor()
    
    cursor.execute('''
    INSERT INTO task_progress_logs
    (sub_task_id, previous_status, new_status, progress_value, comments, logged_by, time_spent_minutes)
    VALUES (%s, %s, %s, %s, %s, %s, %s)
    ''', (sub_task_id, previous_status, new_status, progress, comments, logged_by, time_spent))
    
    conn.commit()

def update_task_progress(task_id, progress, status=None, comments=None, logged_by='system', time_spent=0):
    """
    更新任务状态，并记录进度日志
    
    Args:
        task_id: 子任务ID
        progress: 进度百分比 (0-100)，仅用于日志记录
        status: 任务状态 (completed, pending, in_progress, blocked, failed)
        comments: 进度更新备注
        logged_by: 记录人
        time_spent: 花费时间(分钟)
        
    Returns:
        bool: 更新成功返回True，否则返回False
    """
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 检查任务是否存在
    cursor.execute('SELECT * FROM sub_tasks WHERE id = %s', (task_id,))
    task = cursor.fetchone()
    
    if not task:
        return False
    
    # 如果未指定状态，保持原状态
    if not status:
        status = task['status']
    
    # 更新任务状态
    cursor.execute('''
    UPDATE sub_tasks 
    SET status = %s, updated_at = %s
    WHERE id = %s
    ''', (status, datetime.datetime.now(), task_id))
    
    # 记录进度日志
    cursor.execute('''
    INSERT INTO task_progress_logs
    (sub_task_id, progress_value, new_status, previous_status, comments, logged_by, time_spent_minutes, log_time)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
    ''', (
        task_id, 
        progress, 
        status,
        task['status'],
        comments or '进度更新', 
        logged_by, 
        time_spent,
        datetime.datetime.now()
    ))
    
    # 提交事务
    conn.commit()
    
    return True

def check_task_dependencies(task_id):
    """
    检查任务的所有依赖是否都已完成
    
    Args:
        task_id: 子任务ID
        
    Returns:
        bool: 如果所有依赖都已完成则返回True，否则返回False
    """
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取所有依赖任务
    cursor.execute('''
    SELECT td.dependency_task_id, st.status
    FROM task_dependencies td
    JOIN sub_tasks st ON td.dependency_task_id = st.id
    WHERE td.dependent_task_id = %s
    ''', (task_id,))
    
    dependencies = cursor.fetchall()
    
    # 检查所有依赖是否完成
    for dep in dependencies:
        if dep['status'] != 'completed':
            return False
    
    return True

def add_task_dependency(dependent_task_id, dependency_task_id, dependency_type='finish_to_start', is_critical=False):
    """添加任务之间的依赖关系"""
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    try:
        cursor.execute('''
        INSERT INTO task_dependencies
        (dependent_task_id, dependency_task_id, dependency_type, is_critical)
        VALUES (%s, %s, %s, %s)
        RETURNING *
        ''', (dependent_task_id, dependency_task_id, dependency_type, is_critical))
        
        dependency = cursor.fetchone()
        conn.commit()
        return dependency
    except Exception as e:
        conn.rollback()
        print(f"添加任务依赖出错: {str(e)}")
        return None

def record_file_change(execution_id, file_path, change_type, content_before=None, content_after=None):
    """记录文件变更"""
    conn = g.db
    cursor = conn.cursor()
    
    cursor.execute('''
    INSERT INTO file_changes 
    (execution_id, file_path, change_type, content_before, content_after)
    VALUES (%s, %s, %s, %s, %s)
    ''', (execution_id, file_path, change_type, content_before, content_after))
    
    conn.commit()

def format_datetime(dt):
    """格式化日期时间为字符串"""
    if dt:
        return dt.strftime('%Y-%m-%d %H:%M:%S')
    return None

def format_file_size(size_bytes):
    """格式化文件大小显示"""
    if size_bytes < 1024:
        return f"{size_bytes} B"
    elif size_bytes < 1024 * 1024:
        return f"{size_bytes/1024:.2f} KB"
    elif size_bytes < 1024 * 1024 * 1024:
        return f"{size_bytes/(1024*1024):.2f} MB"
    else:
        return f"{size_bytes/(1024*1024*1024):.2f} GB" 